import java.util.Arrays;
import java.util.Comparator;

//Exercise threads 7b
//from book french Benmammar Threads, page 137


public class Factorial4 extends Thread{

int pos=0; //position in ranking: 1..4
static final int nThreads = 4; static final int base = 4;
int n; // for factorial(n), e.g., n=3 => factorial(3)=6

public int getPos() {return pos;}
public void setPos(int pos) {this.pos = pos;}

public int getN() { return n;}
public void setN(int n) {this.n = n;}

public long getResult() {return result;}
public void setResult(long result) { this.result = result;}

public int getTime() { return time;}
public void setTime(int time) {this.time = time;}

long result =1; // to hold result
int time =0; // time elapsed to compute factorial

public Factorial4(int n) { this.setN(n);}


private void setResults(long r, int t) { 
	//thread method => not static

	System.out.println("Factorial("+this.n + ")= "+ r +
" and lasts "+ t + " nSeconds.");
	this.setResult(r); this.setTime(t);
}


public void run() {

	int[] timeSpent = new int[1]; long r;//r=result
	r= computeFactorial(this.getN(), timeSpent);//synchronized,locked
	setResults(r, timeSpent[0]);
}

// test of 'synchronized'. Theory:
// instance method without shared resources => no effet
// but code segment is unique for all threads


private long computeFactorial(int n, int[] timeSpent) {

// private synchronized long computeFactorial(int n, int[] timeSpent) {
	long begin = System.nanoTime();
	long r =1; for (int i=2; i<= n; i++) {r*=i;}
	long ellapsed = System.nanoTime();
	timeSpent[0] = (int)(ellapsed - begin);
	return r;
}


private static void runFactorialThreads(Factorial4[] f) {

	for (int i=0; i< nThreads; i++) {
		f[i]= new Factorial4 ((int)(base+i));}

	for (int i=0; i< nThreads; i++) {f[i].start();}

	for (int i=0; i< nThreads; i++) {
		try {
			f[i].join();
			System.out.println(" fact("+(int)(base+i) +
") finished (join), at time: "+ (int)(f[i].getTime()) + " .");
		} 
		catch(Exception e) {}
	}
}


private static void toString(Factorial4[] f, int i) {

	System.out.println("Factorial("+f[i].getN() +
")= " + f[i].getResult() + " and last " + f[i].getTime() +
" nSeconds. Pos nr. " + f[i].getPos() + " .");
}


//main help method => static
private static void sortByTimeAndDisplay(Factorial4[] f) {

	System.out.println("It was: unsorted");
	Arrays.sort(f, new SortFactbyTime ()); 
	//sort by ascending time

	System.out.println("\nNow: Sorted by Time elapsed, in nSeconds. \n");
	for (int i = 0; i <f.length; i++) {
		try { f[i].setPos((int)(i+1)); } 
		catch(Exception e) {}
	}
	for (int i = 0; i < f.length; i++){ toString(f,i); }
}


private static void finalRemarksThreads(Factorial4[] f) {

	// for test purposes
	/* try{f[0].setN(4);f[0].setPos(1);f[1].setN(5);f[1].setPos(2);
	f[2].setN(6);f[2].setPos(3);f[3].setN(7);f[3].setPos(4);
	} catch(Exception e) {};
	*/

	if (((f[0].getN()==4) && (f[0].getPos()==1)) &&
	((f[1].getN()==5) && (f[1].getPos()==2))&&
	((f[2].getN()==6) && (f[2].getPos()==3))&&
	((f[3].getN()==7) && (f[3].getPos()==4))){
	System.out.println("\n\nThread A fact(4) is very quick.");
	System.out.println("Thread B fact(5) is quick.");
	System.out.println("Thread C fact(6) is normal.");
	System.out.println("Thread D fact(7) is slow.");
	}
}


private static long computeFactorialStatic(int n, int[] timeSpent) {

	long begin = System.nanoTime();
	long r =1; for (int i=2; i<= n; i++) {r*=i;}
	long ellapsed = System.nanoTime();
	timeSpent[0] = (int)(ellapsed - begin);
	return r;
}


private static void sequencialAnalysis() {

	int[] timeSpent = new int[1]; long r;//r=result
	System.out.print("\n **** Static sequential analysis *** \n \n");

	for (int i=0; i< nThreads; i++) {
		r = computeFactorialStatic((int) (base +i), timeSpent);
		System.out.println("Fact(" + (int) (base +i) + ")= "+ r +
" and lasts "+ timeSpent[0] + " nSeconds.");
}

// r = computeFactorialStatic(4, timeSpent);
// System.out.println("\n Static seq analysis Fact(4)= "+ r +
// " and lasts "+ timeSpent[0] + " nSeconds.");
}


public static void main(String[] args) {
	Factorial4 [] f = new Factorial4 [nThreads] ;
	runFactorialThreads(f);
	sortByTimeAndDisplay(f);
	finalRemarksThreads(f);
	sequencialAnalysis();
}

}


//Helper class to sort by crescent time elapsed
class SortFactbyTime implements Comparator<Factorial4 > {

public int compare(Factorial4 f1, Factorial4 f2){
	return f1.getTime() - f2.getTime();
}

}